import { Leafer, Pen, DragEvent, App } from "leafer-ui";
import { ITool, IToolConfig } from "../types";
export const PenTool: ITool = ({ app, config, historyUtil, box }) => {
  let pen: Pen;
  let isDrawing = false;
  // app.cursor ="grab"
  const initPen = () => {
    pen = new Pen();
    box.add(pen);
  };
  const startDrawing = (e: DragEvent) => {
    if (e?.multiTouch) return (isDrawing = false);
    initPen();
    isDrawing = true;
    const point = e.getPagePoint();
    pen.setStyle({
      stroke: config.pen.color,
      strokeWidth: config.pen.strokeWidth / (app.data?.fitScale ?? 1),
      strokeCap: "round",
      strokeJoin: "round",
      opacity: config.pen.opcity,
    });
    pen.moveTo(point.x, point.y);
  };
  const continueDrawing = (e: DragEvent) => {
    if (e?.multiTouch) return (isDrawing = false);
    if (!isDrawing) return;
    const point = e.getPagePoint();
    pen.lineTo(point.x, point.y);
  };
  const stopDrawing = () => {
    isDrawing = false;
    // pen = null;
    historyUtil.commit(box.toJSON());
  };
  const eventsMap = {
    [DragEvent.START]: startDrawing,
    [DragEvent.DRAG]: continueDrawing,
    [DragEvent.END]: stopDrawing,
  };
  return {
    eventsMap,
    active: () => {},
    deactive: () => {},
  };
};
